<?php

namespace app\index\controller;

use app\common\controller\HomeBase;
use app\common\model\User;
use app\common\model\Qqconnect;
use qqconnect\QC;
use think\Cache;
use think\Db;

class Applogin extends HomeBase
{
    protected $config;

    protected function _initialize()
    {
        parent::_initialize();
        $qqlogin_config = Db::name('system')->field('value')->where('name', 'qqlogin')->find();
        $config = unserialize($qqlogin_config['value']);
        $config['scope'] = 'get_user_info,add_share,list_album,add_album,upload_pic,add_topic,add_one_blog,add_weibo,check_page_fans,add_t,add_pic_t,del_t,get_repost_list,get_info,get_other_info,get_fanslist,get_idolist,add_idol,del_idol,get_tenpay_addr';
        $config['errorReport'] = true;
        $this->config = $config;
        session('qqconnect', $config);
    }

    public function qqcallback()
    {
        $qc = new QC();
        $access_token = $qc->qq_callback(); // openid
        $openid = $qc->get_openid(); // openid
        $qc = new QC($access_token, $openid);
        $info = $qc->get_user_info(); // access_token
        if ($info['ret'] < 0) {
            $this->error('获取用户信息失败');
        } else {
            $connect = (new Qqconnect())->where('qq_openid', $openid)->find();
            if(!$connect){
                //判断userId在不在，如果在
                if(session('userid')&&session('qqopenid')){
                    //旧的
                    $connect = (new Qqconnect())->where('user_id', session('userid'))->find();
                    $connect->qq_openid=$openid;
                    $connect->nickname=$info['nickname'];
                    $connect->userhead= $info['figureurl_2'];
                    $connect->save();
                    session('qqopenid', $openid);
                    $this->redirect('index/user/safe');
                }elseif(session('userid')&&!session('qqopenid')){
                    //旧的
                    $connect=(new Qqconnect());
                    $connect->qq_openid=$openid;
                    $connect->nickname=$info['nickname'];
                    $connect->userhead= $info['figureurl_2'];
                    $connect->user_id== session('userid');
                    $connect->save();
                    session('qqopenid', $openid);
                }else {
                    //首次登陆
                    $userdata['uuid'] = guid();
                    $userdata['username'] = 'u_' . generate_password(4);
                    $userdata['nickname'] = $info['nickname'] . generate_password(4);
                    $userdata['avatar'] = $info['figureurl_2'];
                    $userdata['status'] = 1;
                    $userdata['reg_ip'] = $_SERVER['REMOTE_ADDR'];
                    $userdata['updated_at'] = $userdata['last_login_time'] = date('Y-m-d H:i:s');
                    $userNew = User::create($userdata);

                    $data['userhead'] = $info['figureurl_2'];
                    $data['nickname'] = $info['nickname'];
                    $data['status'] = 1;
                    $data['errorcode'] = 0;
                    $data['qq_openid'] = $openid;
                    $data['user_id'] = $userNew->id;
                    Qqconnect::create($data);

                    session('designation', '普通用户');
                    session('userid', $userNew->id);
                    session('username', $userNew->username);
                    session('nickname', $userNew->nickname);
                    session('avatar', $userNew->avatar);
                    session('uuid', $userNew->uuid);
                    session('posted_num', 0);
                    session('passed_num', 0);
                    session('praise_num', 0);
                    session('qqopenid', $openid);
                    $this->redirect(url('index/user/winfo'));
                }
            }else {
                //没有UID有互联记录
                if(session('userid')){

                    if(session('userid')!=$connect->user_id) {
                        $msg='这个QQ已经绑定过用户了，如需要 请先去解绑';
                    }else{
                        $msg='你这么重复的玩有意思吗';
                    }
                    return $this->error($msg, 'index/index/index');
                }


                $user = (new User())->where('id', $connect->user_id)->find();
                if ($user && $user->status > 0) {
                    session('uuid', $user->uuid);
                    session('passed_num', $user->passed_num);
                    session('praise_num', $user->praise_num);
                    session('designation', $user['designation']);
                    session('userid', $user['id']);
                    session('nickname', $user['nickname']);
                    session('avatar', $user['avatar']);
                    session('posted_num', $user['posted_num']);
                    session('passed_num', $user['passed_num']);
                    session('praise_num', $user['praise_num']);
                    session('qqopenid', $openid);
                    session('no_audit', $user['no_audit']);
                    $user->save(
                        [
                            'last_login_time' => date('Y-m-d H:i:s'),
                            'last_login_ip' => $this->request->ip(),
                        ]
                    );
                }else{
                    return $this->error('用户状态不能登陆，请联系管理', 'index/index/index');
                }
            }
            $this->redirect(session('callbackurl'));
        }
    }

    public function unbind()
    {
        $uid = session('userid');
        $info = Db::name('user')->where('id', $uid)->find();
        if ($info['password'] == 0) {
            return array('code' => 2, 'msg' => '请先设置密码，然后再解除绑定', 'data' => []);
        } else {
            if ($info['status'] < 2) {
                return array('code' => 2, 'msg' => '必须是邮箱已验证的情况下才可以解绑！', 'data' => []);
            } else {
                (new Qqconnect())->where('user_id', $uid)->delete();
                session('qqopenid', null);
                return array('code' => 1, 'msg' => '解除绑定成功', 'data' => []);
            }
        }
    }

    //绑定qq号
    public function qqlogin()
    {

        session('callbackurl', isset($_SERVER['HTTP_REFERER']) ? @$_SERVER['HTTP_REFERER'] : url('index/index/index'));
        $qc = new QC();
        $this->redirect($qc->qq_login());
    }
}
